<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Translate extends Admin_Controller {

    protected $data;

    function __construct() {
        parent::__construct();
        $this->load->model(array("Mtranslate","Mlanguage"));
    }

    public function index() {
        $this->Mtranslate->export_json();
		$this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
		$this->breadcrumb->append_crumb(trans('breadcrumb_translate'),base_url().'admincp/translate');
		$dataLang = $this->registry->get('language');
		$maxLang = count($dataLang);
    	if($this->input->is_ajax_request()){
            $start = $this->input->post('iDisplayStart');
            $length = $this->input->post('iDisplayLength');
            $sSearch = $this->input->get_post('sSearch', true);
            $sEcho = $this->input->get_post('sEcho', true);
            // $myFilter = $this->input->get_post('myFilter', true);
            $selectBeforeFrom = '';
            $selectAfterFrom = '';
            $where = '1=1';
            $dataColums = array('a1.word');
            $i=1;
            foreach($dataLang as $lang){
            	$i_next = $i + 1;
            	if($i == 1){
            		$selectBeforeFrom .= 'a1.tran_id, a1.word as keyword, a'.$i.'.translate as translate_'.$lang['lang_code'];
            		$selectAfterFrom .= '(select * from tpt_translate where lang_code = "'.$lang['lang_code'].'") a1';
            		$where .= ' AND a1.tran_id = a'.$i_next.'.tran_id';
            	}else{
            		$selectBeforeFrom .= ', a'.$i.'.translate as translate_'.$lang['lang_code'];	
            		$selectAfterFrom .= ', (select * from tpt_translate where lang_code = "'.$lang['lang_code'].'") a'.$i;
            		if($i == $maxLang){
            			$i_next = 1;
	            	}
	            	$where .= ' AND a'.$i.'.tran_id = a'.$i_next.'.tran_id';
            	}
                $dataColums[] = 'a'.$i.'.translate';
            	$i++;
            }

            $sql = "select ".$selectBeforeFrom." from ".$selectAfterFrom." where ".$where;
            $iTotal = $this->db->query($sql)->num_rows();

            /* 
             * Filtering
             * NOTE this does not match the built-in DataTables filtering which does it
             * word by word on any field. It's possible to do here, but concerned about efficiency
             * on very large tables, and MySQL's regex functionality is very limited
             */

            $orLike = '';
            if(isset($sSearch) && !empty($sSearch))
            {
                $orLike = ' AND (';
                for($i=0; $i<count($dataColums); $i++)
                {
                    $bSearchable = $this->input->get_post('bSearchable_'.$i, true);
                    
                    // Individual column filtering
                    if(isset($bSearchable) && $bSearchable == 'true')
                    {
                        // $this->db->or_like($dataColums[$i], $this->db->escape_like_str($sSearch));
                        if($i==0){
                            $orLike .= $dataColums[$i].' LIKE "%'.$this->db->escape_like_str($sSearch).'%"';
                        }else{
                            $orLike .= ' OR '.$dataColums[$i].' LIKE "%'.$this->db->escape_like_str($sSearch).'%"';
                        }
                    }
                }
                $orLike .= ')';
            }

            $sql = "select SQL_CALC_FOUND_ROWS ".$selectBeforeFrom." from ".$selectAfterFrom."
where ".$where.$orLike." ORDER BY a1.tran_id DESC LIMIT $start, $length";

            $data['list_translate'] = $this->db->query($sql)->result_array();
            $sql = "SELECT FOUND_ROWS() AS total";
            $rows = $this->db->query($sql)->row_array();

            if ((isset($data['list_translate']) == TRUE) && ($data['list_translate'] != '') && (is_array($data['list_translate']) == TRUE)) {
                $aaData = array();                
                foreach ($data['list_translate'] as $key => $value) {
                    $aaData[$key][] = '<td>' . $value['keyword'] . '</td>';
                    foreach($dataLang as $lang){
                    	$aaData[$key][] = '<td>' . $value['translate_'.$lang['lang_code']] . '</td>';
                    }
                    $aaData[$key][] = '<td> <a href="' . base_url() . 'admincp/translate/edit/id/' . $value['tran_id'] . '" class="btn btn-default tip" title="Edit"><i class="icon16 i-pencil"></i></a></td>
                                            <a href="javascript:void(0)" title="Delete" class="btn btn-default tip" onclick="confirm_delete('.$value['tran_id'].',\''.$this->router->fetch_class().'\');"><i class="icon16 i-remove"></i></a></td>';
                }
                $result = array(
                	"aaData" => $aaData,
                    "iTotalRecords" => $iTotal,
                	"iTotalDisplayRecords" => $rows['total']
            	);
            }
            $this->output->set_output(json_encode($result));
        }else{
            $data['template'] = "translate/view";
            $data['title_page']='<i class="icon20 i-transmission"></i> '.trans('title_translate');
            $data['info'] = $dataLang;
        	$this->load->view('admincp/template',$data);
        }
    }

    public function add(){
		$this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
		$this->breadcrumb->append_crumb(trans('breadcrumb_translate'),base_url().'admincp/translate');
		$this->breadcrumb->append_crumb(trans('breadcrumb_translate_add'),base_url().'admincp/translate/add');
    	$data['template']="translate/add";
        $data['title_page']='<i class="icon20 i-plus-circle-2"></i> '.trans('title_translate_add');
        $dataLang = $this->registry->get('language');
        $data['language'] = $dataLang;
		if($this->input->server('REQUEST_METHOD') == "POST"){
            $data_insert['keyword'] = $this->input->post('keyword');
            foreach($dataLang as $lang){
                $data_insert['translate_'.$lang['lang_code']] = $this->input->post('translate_'.$lang['lang_code']);
            }
            $this->Mtranslate->insert($data_insert);
            $this->session->set_flashdata(array("success"=>trans('message_create_successfully')));
            redirect(base_url()."admincp/translate");
        }
		$this->load->view("admincp/template",$data);
    }

    public function edit(){
        $id = $this->uri->segment(5);
		$this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
		$this->breadcrumb->append_crumb(trans('breadcrumb_translate'),base_url().'admincp/translate');
		$this->breadcrumb->append_crumb(trans('breadcrumb_translate_edit'),base_url().'admincp/translate/edit/id/'.$id);
    	$data['template']="translate/edit";
        $data['title_page']='<i class="icon20 i-pen-2"></i> '.trans('title_translate_edit');
        $dataLang = $this->registry->get('language');
        $data['language'] = $dataLang;
    	$data['info'] = $this->Mtranslate->get_data($id);
		if($this->input->server('REQUEST_METHOD') == "POST"){
			$data_update['keyword'] = $this->input->post('keyword');
            foreach($dataLang as $lang){
                $data_update['translate_'.$lang['lang_code']] = $this->input->post('translate_'.$lang['lang_code']);
            }
			$this->Mtranslate->update($data_update,$id);
			$this->session->set_flashdata("success", trans('message_edit_successfully'));
			redirect(base_url()."admincp/translate");
		}
		$this->load->view("admincp/template",$data);
    }

    public function getTrans() {
        if ($this->input->is_ajax_request()) {
            $word = $this->input->post('word');
            echo $this->translate->get($word);
        }
    }
	
	public function delete(){
		$id = $this->uri->segment(5);
		$this->Mtranslate->delete($id);
		$this->session->set_flashdata(array("success"=>trans('message_delete_successfully')));
		redirect(base_url()."admincp/translate");
	}
}